import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../../../util/ImConstant.dart';
import '../../../util/LoggerUtil.dart';

class TextViewPage extends StatefulWidget {
  final String title;
  final String filePath;

  const TextViewPage({required this.title, required this.filePath, super.key});

  @override
  State<StatefulWidget> createState() => _TextViewState();
}

class _TextViewState extends State<TextViewPage> {

  final _logger = createLogger();
  String _text = '';

  @override
  void initState() {
    super.initState();

    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: _buildAppBar(context),
        backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
            child: Text(
              _text,
              style: const TextStyle(
                fontSize: ImConstant.IM_DEFAULT_SIZE,
                fontWeight: FontWeight.bold,
                color: Colors.green,
              ),
            ),
          ),
        )
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      leading: GestureDetector(
        child: const Icon(Icons.chevron_left, color: Colors.black),
        onTap: () => Navigator.of(context).pop(),
      ),
      centerTitle: true,
      title: Text(
        widget.title,
        style: const TextStyle(color: Colors.black, fontSize: ImConstant.IM_DEFAULT_SIZE),
      ),
    );
  }

  _loadData() async {
    var file = File(widget.filePath);
    try {
      String text = await file.readAsString(encoding: Encoding.getByName('utf-8')!);
      setState(() {
        _text = text;
      });
    } catch (error, stracktrace) {
      _logger.e('read file error', error: error, stackTrace: stracktrace);
    }

  }
}
